package com.jirefox.loner.daemon.initialize;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.jirefox.loner.daemon.model.WorkDir;

@Configuration
public class InitWorkDir {

	private final Logger logger = LoggerFactory.getLogger(InitWorkDir.class);

	@Value("${loner.workdir:/work}")
	private String workdir;

	@Bean
	public WorkDir workDir() {
		ApplicationHome home = new ApplicationHome();
		String daemonDir = home.getDir().getAbsolutePath();
		String baseDir = daemonDir + workdir;
		WorkDir workDir = new WorkDir(baseDir);
		File workFolder = new File(baseDir);
		if (!workFolder.exists()) {
			workFolder.mkdirs();
		}
		if (!workFolder.isDirectory()) {
			logger.error("loner.workdir:{} should be an folder ,not a file", workFolder.getAbsolutePath());
			throw new RuntimeException(
					"loner.workdir:" + workFolder.getAbsolutePath() + "should be a folder, not a file");
		}

		File driversFolder = new File(workDir.driversDir());
		if (!driversFolder.exists()) {
			driversFolder.mkdirs();
		}

		File appsFolder = new File(workDir.appsDir());
		if (!appsFolder.exists()) {
			appsFolder.mkdirs();
		}

		return workDir;
	}

}
